package com.lzy.controller.interceptor;

import com.lzy.base.BaseInfoProperties;
import com.lzy.exceptions.GraceException;
import com.lzy.grace.result.ResponseStatusEnum;
import com.lzy.utils.IPUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
public class SMSInterceptor extends BaseInfoProperties implements HandlerInterceptor {

    /**
     * 拦截请求,在controller调用方法之前
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 获得用户的手机号
        //String userIP = IPUtil.getRequestIp(request);
        String mobile = request.getParameter("mobile");
        // 判断手机号是否处于黑名单中
        boolean keyIsExist = redis.keyIsExist(MOBILE_SMSCODE + "limit:" + mobile);

        // 如果存在黑名单中则拦截请求
        if (keyIsExist) {
            GraceException.display(ResponseStatusEnum.SMS_NEED_WAIT_ERROR);
            System.out.println("短信发送频率太大！");
            return false;
        }
        return true;
    }

    /**
     * 请求controller调用方法之后,渲染视图之前
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }


    /**
     * 请求controller之后,渲染视图之后
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
